package com.googlecode.lucene.appengine;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Id;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Cached;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Parent;
import com.googlecode.objectify.annotation.Unindexed;

@Entity
@Unindexed
@Cached
class Segment {
	
	private static final Logger log = LoggerFactory.getLogger(Segment.class);
	
	@Parent
	Key<LuceneIndex> index;
	
	@Id
	String name;
	
	long length;
	
	long lastModified;
	
	long hunkCount;

	@SuppressWarnings("unused")
	private Segment() {/* objectify */}
	
	public Segment(Key<LuceneIndex> index, String name) {
		this.name = name;
		this.index = index;
	}
	
	public SegmentHunk getHunk(int index) {//GAE id cannotstart from zero
		return GaeObjectifyFactory.getInstance().begin().get(buildSegmentHunkKey(index));
	}
	
	public SegmentHunk newHunk() {
		hunkCount++;
		log.debug("Created Hunk '{}-{}-{}'.", new Object[] {index.getName(), name, hunkCount});
		final SegmentHunk newHunk = new SegmentHunk(getKey(), hunkCount);
		
		//TODO: refactor
		GaeObjectifyFactory.getInstance().begin().put(newHunk);
		
		lastModified = System.currentTimeMillis();
		
		return newHunk;
	}
	
	List<Key<SegmentHunk>> getHunkKeys(Key<Segment> currentKey) {
		List<Key<SegmentHunk>> hunkKeys = new ArrayList<Key<SegmentHunk>>((int) hunkCount);
		for (int i = 0; i < hunkCount; i++) {
			hunkKeys.add(new Key<SegmentHunk>(currentKey, SegmentHunk.class, i + 1));
		}
		return hunkKeys;
	}
	
	private Key<SegmentHunk> buildSegmentHunkKey(int index) {
		return new Key<SegmentHunk>(getKey(), SegmentHunk.class, index + 1);
	}
	private Key<Segment> getKey() {
		return new Key<Segment>(index, Segment.class, name);
	}
	
	@Override
	public String toString() {
		return index.getName() + "->" + name;
	}

}
